/**
 * <p>功能:系统管理模块-权限管理-用户管理 <p>
 * @extends Wys.basic.BaseView
 * @author wys
 */
Ext.define('Jason.view.protal.module.systemManager.right.users.MainCtrl', {
    extend: 'Wys.basic.BaseCtrl',
    alias: 'controller.right_users_MainViewCtrl',
    /* private */
    getMainView: function () {
        return {
            tree: this.getView(),
            gridPanel: this.getView().down('#usersGrid')
        };
    },
    formItems: function () { /** 表单信息*/
        return [{
            xtype: 'fieldset',
            title: '员工核心信息',
            collapsible: false,
            defaultType: 'textfield',
            layout: {
                type: 'table',
                columns: 3
            },
            defaults: {
                width: '100%',
                labelWidth: 80
            },
            items: [
                { xtype: 'textfield', fieldLabel: '登录名', name: 'loginname', allowBlank: false, afterLabelTextTpl: cfg.required, blankText: '登录名不能为空' },
                { xtype: 'textfield', fieldLabel: '登录密码', name: 'password', allowBlank: false, afterLabelTextTpl: cfg.required, blankText: '登录密码不能为空', inputType: 'password' },
                { xtype: 'textfield', fieldLabel: '确认密码', name: 'password2', allowBlank: false, afterLabelTextTpl: cfg.required, blankText: '请再次输入密码', inputType: 'password', vtype: 'repetition', repetition: { targetCmpId: 'password' } },
                {
                    xtype: 'comboTree',
                    valueField: 'id',
                    displayField: 'deptname',
                    store: Ext.create('Ext.data.TreeStore', {
                        fields: [
                            { name: 'id', mapping: 'id' },
                            { name: 'text', mapping: 'deptname' },
                            'children',
                            'leaf'
                        ],
                        autoLoad: true,
                        rootVisible: true,
                        proxy: {
                            type: 'ajax',
                            url: reqUrl.sys.organize.leftMenu,
                            rootProperty: function (data) {
                                return data;
                            }
                        }
                    }),
                    listeners: {
                    },
                    allowBlank: false,
                    afterLabelTextTpl: cfg.required,
                    name: 'deptcode',
                    emptyText: '请选择...',
                    fieldLabel: '所属部门'
                },{
                    xtype: 'RemoteCombobox',
                    name: 'post',
                    emptyText: '请选择职务...',
                    model: Ext.create('Ext.data.Model', {
                        fields: ['key', 'value']
                    }),
                    valueField: 'value',
                    displayField: 'key',
                    proxy_url: reqUrl.sys.comboData.dict + "Duty",
                    allowBlank: false,
                    afterLabelTextTpl: cfg.required,
                    blankText: '职务不能为空',
                    fieldLabel: '职务',
                    value: 1
                }, {
                    xtype: 'RemoteCombobox',
                    name: 'theme',
                    model: Ext.create('Ext.data.Model', {
                        fields: ['key', 'value']
                    }),
                    fieldLabel: '默认主题',
                    valueField: 'value',
                    displayField: 'key',
                    proxy_url: reqUrl.sys.comboData.dict + "Theme",
                    allowBlank: false,
                    value: 'systemManager'
                }
            ]
        }, {
            xtype: 'fieldset',
            title: '人员基本信息',
            collapsible: true,
            defaultType: 'textfield',
            layout: {
                type: 'table',
                columns: 3
            },
            defaults: {
                width: '100%',
                labelWidth: 80
            },
            items: [
                { xtype: 'textfield', fieldLabel: '姓名', name: 'realname', allowBlank: false, afterLabelTextTpl: cfg.required, blankText: '真实姓名不能为空', maxLength: '50', maxLengthText: '姓名不能超过五十个字' },
                { xtype: 'textfield', fieldLabel: '身份证号', name: 'idcard', allowBlank: true, afterLabelTextTpl: cfg.required, blankText: '身份证号不能为空', vtype: 'cardText' },
                {
                    xtype: 'RemoteCombobox',
                    name: 'sex',
                    emptyText: '请选择性别...',
                    model: Ext.create('Ext.data.Model', {
                        fields: ['key', 'value']
                    }),
                    valueField: 'value',
                    displayField: 'key',
                    proxy_url: reqUrl.sys.comboData.dict + "Gender",
                    allowBlank: false,
                    afterLabelTextTpl: cfg.required,
                    blankText: '性别不能为空',
                    fieldLabel: '性别',
                    value: 1
                },
                { xtype: 'textfield', fieldLabel: '办公电话', name: 'tel', allowBlank: true, blankText: '办公电话不能为空', regex: /^((0[1-9]{3})?(0[12][0-9])?[-])?\d{6,8}$/, regexText: '请输入正确的电话号码,如:0920-29392929' },
                { xtype: 'textfield', fieldLabel: '个人电话', name: 'mobphone', allowBlank: true, blankText: '个人电话不能为空', maxLength: '11', maxLengthText: '电话号码不得超过十一位数', regex: /(^0?[1][35][0-9]{9}$)/, regexText: '电话号码格式错误' },
                { xtype: 'textfield', fieldLabel: 'QQ号', name: 'qq', allowBlank: true, blankText: 'QQ号不能为空', maxLength: '12', minLength: '6', maxLengthText: 'QQ号不得超过十一位数', minLengthText: 'QQ号不得少于六位数', regex: /^[1-9]\d{4,11}$/, regexText: 'QQ号格式错误' },
                { xtype: 'textfield', fieldLabel: '电子邮箱', name: 'email', allowBlank: true, blankText: '电子邮箱不能为空', vtype: 'email', vtypeText: '该输入项必须是电子邮箱地址,格式例如：xxx@xxx.com' },
                {
                    xtype: 'RemoteCombobox',
                    name: 'jobstate',
                    emptyText: '请选择工作状态...',
                    model: Ext.create('Ext.data.Model', {
                        fields: ['key', 'value']
                    }),
                    valueField: 'value',
                    displayField: 'key',
                    proxy_url: reqUrl.sys.comboData.dict + "UserStatus",
                    allowBlank: false,
                    afterLabelTextTpl: cfg.required,
                    blankText: '工作状态不能为空',
                    fieldLabel: '工作状态',
                    value: 1
                }, {
                    xtype: 'RemoteCombobox',
                    name: 'nation',
                    emptyText: '请选择民族...',
                    model: Ext.create('Ext.data.Model', {
                        fields: ['key', 'value']
                    }),
                    valueField: 'value',
                    displayField: 'key',
                    proxy_url: reqUrl.sys.comboData.dict + "NATION",
                    allowBlank: false,
                    afterLabelTextTpl: cfg.required,
                    blankText: '民族不能为空',
                    fieldLabel: '民族',
                    value: 36
                }, {
                    name: 'bindClientIp',
                    fieldLabel: '客户端IP',
                    emptyText: '如果输入则表示此账户只能在此IP地址的客户端进行访问'
                }, {
                    name: 'signPic',
                    fieldLabel: '签名图',
                    colspan: 2,
                    xtype: 'uploadField'
                }
            ]
        }];
    },
    onNewButtonClick: function (btn) {
        var me = this;
        Ext.create('Wys.form.FormWindow', {
            width: 840,
            title: '系统用户管理信息',
            config: {
                operatetype: 'new',
                model: 'Jason.model.protal.module.systemManager.right.users.UserModel',
                gridPanel: btn.up('#usersGrid'),
                items: me.formItems()
            }
        }).show()
    },
    onEditButtonClick: function (grid, record) {
        var me = this;
        if (grid.xtype.indexOf('button') != -1) {
            records = grid.up('baseView').getSelection();
            if (records.length === 0 || records.length > 1) {
                EUtil.toastWarn('请选择要编辑的数据。<br /><span style="color:red">注：一次只能选择一条数据进行编辑</span>');
                return;
            } else {
                record = records[0];
            }
        }
        record.set('password', '');//重置密码
        var grid = me.getView().down('#usersGrid');
        Ext.create('Wys.form.FormWindow', {
            width: 840,
            title: ' 『' + record.get('realname') + '』用户 信息',
            config: {
                model: 'Jason.model.protal.module.systemManager.right.users.UserModel',
                operatetype: 'edit',
                gridPanel: grid,
                items: me.formItems(),
                formData: grid //传入grid可启用上一页下一页
            }
        }).show();
    },
    onDeleteButtonClick: function (btn) {
        var me = this,
            store = me.getMainView().gridPanel.getStore();
        records = me.getMainView().gridPanel.getSelection(),
            userName = [], userCode = [];
        Ext.Array.each(records, function (item) {
            userName.push(item.data.realname);
            userCode.push(item.data.id);
        });
        if (records.length === 0) {
            EUtil.toastWarn('请先选中您想要移除的用户信息');
            return;
        }
        EUtil.showMsg({
            option: 3,
            title: '温馨提示',
            message: Ext.String.format('确定要删除用户<span style="color:red;">『{0}』</span>吗？', userName.join()),
            callback: function (btn) {
                if (btn === 'ok') {
                    store.remove(records);
                    store.sync({
                        callback: function () {
                            store.reload();
                        }
                    });
                }
            }
        });
    },
    /** 修改用户状态*/
    onChangeUserState: function (btn) {
        var me = this,
            changeType = btn.itemId,
            records = me.getMainView().gridPanel.getSelectValues(),
            userName = [], userCode = [];
        Ext.Array.each(records, function (item) {
            userName.push(item.realname);
            userCode.push(item.id);
        });
        if (changeType === 'disabled') { /*禁用*/
            if (records.length === 0) {
                EUtil.toastWarn('请先选中您想要禁用的用户信息');
                return;
            }
            EUtil.showMsg({
                option: 3,
                message: Ext.String.format('确定要禁用用<span style="color:red;">『{0}』</span>吗？', userName.join()),
                callback: function (btn) {
                    if (btn === 'ok') {
                        me.onChangeUserStateRS(userCode.join(), 3, me.getMainView().gridPanel, userName.join());
                    }
                }
            });
        }
        if (changeType === 'enabled') { /* 启用 */
            if (records.length === 0) {
                EUtil.toastWarn('请先选中您想要启用的用户信息');
                return;
            }
            EUtil.showMsg({
                option: 3,
                message: Ext.String.format('确定要启用用<span style="color:blue;">『{0}』</span>吗？', userName.join()),
                callback: function (btn) {
                    if (btn === 'ok') {
                        me.onChangeUserStateRS(userCode.join(), 1, me.getMainView().gridPanel, userName.join());
                    }
                }
            });
        }
    },
    onChangeUserStateRS: function (usercode, state, view, userName) {
        EUtil.RS({
            url: reqUrl.sys.user.changeState,
            params: {
                id: usercode,
                state: state
            },
            callback: function (res) {
                if (res.success) {
                    EUtil.toastInfo('用户『' + userName + '』状态已变更');
                    view.refresh();
                } else {
                    EUtil.toastError('用户『' + userName + '』状态变更失败，请稍后再试');
                }
            }
        })
    },
    /** 重置密码*/
    onResetPwd: function (btn) {
        var me = this,
            changeType = btn.itemId,
            records = me.getMainView().gridPanel.getSelectValues(),
            userName = [], userCode = [];
        Ext.Array.each(records, function (item) {
            userName.push(item.realname);
            userCode.push(item.id);
        });
        if (records.length === 0) {
            EUtil.toastWarn('请先选中您想要重置密码的用户信息');
            return;
        }
        EUtil.showMsg({
            option: 3,
            message: Ext.String.format('确定要重置用户<span style="color:red;">『{0}』的登录密码</span>吗？', userName.join()),
            callback: function (btn) {
                if (btn === 'ok') {
                    EUtil.RS({
                        url: reqUrl.sys.user.resetPassword,
                        params: {
                            id: userCode.join(),
                            password: cfg.defaultLoginPwd
                        },
                        callback: function (res) {
                            if (res.success) {
                                EUtil.toastInfo('用户『' + userName.join() + '』密码已重置为' + cfg.defaultLoginPwd);
                            } else {
                                EUtil.toastError('用户『' + userName.join() + '』密码重置失败，请稍后再试');
                            }
                        }
                    })
                }
            }
        });
    },
    refreshLeftMenuTree: function (btn) {
        var treeStore = btn.up('treepanel').getStore();
        treeStore.load();
    },
    onTreeNodeClick: function (node, e) {
        var self = this;
        self.getView().down('#usersGrid').load({
            deptcode: e.get('id')
        });
    }
});